﻿var postData = { "Head": { "Version": "1.0", "Token": "", "AppType": (window.config && window.config.appType) ? window.config.appType : 4 }, "Content": "" };

QueryString.Initial();
var newLinkSource = QueryString.GetValue("hmsr") || "", oldLinkSource = localStorage.getItem('LinkSource') || '';
if ((newLinkSource && oldLinkSource && newLinkSource != oldLinkSource) || (newLinkSource && !oldLinkSource)) {
    localStorage.setItem('LinkSource', newLinkSource);
};

//var globalAjaxFlag = false; // 判断unLoginSearchInforApply的ajax是否请求完成
var unLoginSearchInfor = localStorage.getItem('unLoginSearchInfor');
unLoginSearchInfor = unLoginSearchInfor ? JSON.parse(unLoginSearchInfor) :
[
    { 'Key': 'LoanAmount', 'Value': 10 },
    { 'Key': 'LoanPerod', 'Value': 12 },
    { 'Key': 'Identity', 'Value': '' },
    { 'Key': 'CompanyLocation', 'Value': '' },
    { 'Key': 'BusinessYear', 'Value': '' },
    { 'Key': 'IncomeDistributionType', 'Value': '' },
    { 'Key': 'WorkingAge', 'Value': '' },
    { 'Key': 'SocialSecurityFund', 'Value': '' },
    { 'Key': 'CreditStanding', 'Value': '' },
    { 'Key': 'HaveHouse', 'Value': '' },
    { 'Key': 'HaveCar', 'Value': '' }
]

var LoginSearchInfor = localStorage.getItem('LoginSearchInfor');
LoginSearchInfor = LoginSearchInfor ? JSON.parse(LoginSearchInfor) : {
    'LoanAmount': 10, 'CreditPeriod': 12, 'IDType': null,
    'CompanyLocation': null, 'BusinessYear': null,
    'IncomeDistributionType': null, 'Salary': null, 'WorkingAge': null, 'SocialSecurityFund': null,
    'CreditStanding': null, 'HouseType': null, 'HaveCar': null,
    'GuranteeType': null, 'RepayMentType': null, 'SortType': 0, 'OrgType': null
}

function unLoginSearchInforApply(data, fn) {
    var k = 0;
    for (i = 0; i < unLoginSearchInfor.length; i++) {
        if (unLoginSearchInfor[i].Value != '') k++;
    };
    if (k > 0) {
        postData.Head = { "Version": "1.0", "Token": data.Content.Token, "AppType": config.appType };
        postData.Content = { 'UserId': data.Content.UserID, "CellPhoneNumber": userInfor.Account, "InfoList": [] };
        var searchArr = [];
        for (var i = 0; i < unLoginSearchInfor.length; i++) {
            if (unLoginSearchInfor[i]['Value'] && unLoginSearchInfor[i]['Value'] != '' && unLoginSearchInfor[i]['Value'] != null) {
                if (unLoginSearchInfor[i]['Key'] != "LoanPerod") searchArr.push(unLoginSearchInfor[i]);
            }
        }
        postData.Content.InfoList = searchArr;
        $.ajax({
            type: 'POST', dataType: 'json',
            url: '/apply/UpdateApplySearchCondition',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: JSON.stringify(postData),
            contentType: 'application/json',
            error: function (data, status, headers, config) {
                showTip(status);
            },
            success: function (data) {
                // globalAjaxFlag = true;
                if (fn) fn();
            }
        });
    } else {
        if (fn) fn();
    }
}

function checkTel(Tel) {
    var myreg = /^1\d{10}$/;
    var errorObj = { showErrorPop: false, errorMsg: "", isPass: true };
    if (Tel == "undefined" || Tel === "") {
        errorObj.showErrorPop = true;
        errorObj.isPass = false;
        errorObj.errorMsg = "手机号码不能为空";
        return errorObj;
    }
    if (!myreg.test(Tel)) {
        errorObj.showErrorPop = true;
        errorObj.isPass = false;
        errorObj.errorMsg = "请输入有效的手机号码";
        return errorObj;
    }
    return errorObj;
};

function checkNickname(Nickname) {
    var nameRegex = /[^a-zA-Z\u4e00-\u9fa5]/;
    var errorObj = { showErrorPop: false, errorMsg: "", isPass: true };
    if (Nickname == "undefined" || Nickname === "") {
        errorObj.showErrorPop = true;
        errorObj.isPass = false;
        errorObj.errorMsg = "请输入称呼";
        return errorObj;
    }
    if (nameRegex.test(Nickname)) {
        errorObj.showErrorPop = true;
        errorObj.isPass = false;
        errorObj.errorMsg = "用户名只允许汉字和英文字母";
        return errorObj;
    }
    return errorObj;
};

function checkCode(Code) {
    var errorObj = { showErrorPop: false, errorMsg: "", isPass: true };
    if (Code == "undefined" || Code === "" || Code === null) {
        errorObj.showErrorPop = true;
        errorObj.isPass = false;
        errorObj.errorMsg = "请输入短信验证码";
        return errorObj;
    }
    if (Code.length < 6) {
        errorObj.showErrorPop = true;
        errorObj.isPass = false;
        errorObj.errorMsg = "短信验证码请输入完整";
        return errorObj;
    }
    return errorObj;
};

function showTip(Msg) {
    $("#showErrorPop").show();
    $("#errorMsg").text(Msg);
    setTimeout(function () { $("#showErrorPop").hide(); }, 2000);
}

var fungetCode = function (handler, callback) {
    handler = handler || { flag: true };
    var sum = 60, $btn = $("#btngetcode");
    $btn.text("(" + 60 + "s)").prop("disabled", true);
    var timer = setInterval(function () {
        if (sum > 1 && handler.flag) {
            sum--;
            $btn.text("(" + sum + "s)").prop("disabled", true);
        }
        else {
            clearInterval(timer);
            $btn.text("点击获取").prop("disabled", false);
            if (sum == 1 && callback) {
                callback();
            }
        }
    }, 1000);
};

//测评入口
function assessEnter(param, code) {
    var assessRefer = window.location;//记录从哪个页面进入测评页面的
    localStorage.setItem('assessRefer', assessRefer);
    if (param && param.indexOf("urlFlag") != -1) {

    } else {
        param = "urlFlag=1";
    }
    var querystring = "";
    if (param && param != "smallloan")
        querystring = "?" + param;
    var userInfor = Storage.get('userInfor');
    if (postData.Head.Token == "" && userInfor.Token) {
        postData.Head.Token = userInfor.Token;
    }
    if (!!userInfor && !!userInfor.Account && userInfor.Account != "undefined" && userInfor.Account !== "") {
        if (code && code == -1) {
            if (navigator.userAgent.indexOf('Android') > -1 && navigator.userAgent.indexOf('UC') > -1) {
                $.ajax({
                    type: 'POST', dataType: 'json',
                    url: ' /Apply/NQuerySixYouApplyInfo',
                    async: false,
                    data: JSON.stringify({ "token": postData.Head.Token }),
                    contentType: 'application/json',
                    error: function (data, status, headers, config) {
                        showTip(status);
                    },
                    success: function (data) {
                        if (data.IsHaveAllSixKey) {
                            window.location = '/Assessment/AssessStep2' + querystring + "#/step2";
                        } else {
                            window.location = '/Assessment/AssessStep2' + querystring;
                        }
                    }
                })
            } else {
                //var newWindow = window.open('_blank');
                //if (!newWindow) {
                $.ajax({
                    type: 'POST', dataType: 'json',
                    url: ' /Apply/NQuerySixYouApplyInfo',
                    async: false,
                    data: JSON.stringify({ "token": postData.Head.Token }),
                    contentType: 'application/json',
                    error: function (data, status, headers, config) {
                        showTip(status);
                    },
                    success: function (data) {
                        if (data.IsHaveAllSixKey) {
                            window.location = '/Assessment/AssessStep2' + querystring + "#/step2";
                        } else {
                            window.location = '/Assessment/AssessStep2' + querystring;
                        }
                    }
                })
                //} else {
                //    newWindow.location = '/Assessment/AssessStep2' + querystring;
                //}
            }
        } else {
            //if (param == undefined && userInfor.LoanAmount <= 2) {
            //    window.location = '/smallloan?fromPage=2';
            //} else {
            if (param == "smallloan") {
                window.location = '/smallloan?fromPage=2';
            } else {
                $.ajax({
                    type: 'POST', dataType: 'json',
                    url: ' /Apply/NQuerySixYouApplyInfo',
                    async: false,
                    data: JSON.stringify({ "token": postData.Head.Token }),
                    contentType: 'application/json',
                    error: function (data, status, headers, config) {
                        showTip(status);
                    },
                    success: function (data) {
                        if (data.IsHaveAllSixKey) {
                            window.location = '/Assessment/AssessStep2' + querystring + "#/step2";
                        } else {
                            window.location = '/Assessment/AssessStep2' + querystring;
                        }
                    }
                })
            }
            //}
        }
        localStorage.setItem('applyThreeSteps', 'false'); // 登录状态下申请流程的步骤只有两部 // localStorage以字符串形成存值
    } else {
        if (code && code == -1) {
            //var newWindow = window.open('_blank');
            //if (!newWindow) {
            //window.location = '/Assessment/AssessStep1' + querystring;
            $.ajax({
                type: 'POST', dataType: 'json',
                url: ' /Apply/NQuerySixYouApplyInfo',
                async: false,
                data: JSON.stringify({ "token": postData.Head.Token }),
                contentType: 'application/json',
                error: function (data, status, headers, config) {
                    showTip(status);
                },
                success: function (data) {
                    if (data.IsHaveAllSixKey) {
                        window.location = '/Assessment/AssessStep2' + querystring + "#/step2";
                    } else {
                        window.location = '/Assessment/assessStep1' + querystring;
                    }
                }
            })
            //} else {
            //    newWindow.location = '/Assessment/AssessStep1' + querystring;
            //}
        } else {
            //window.location = '/Assessment/AssessStep1' + querystring;
            $.ajax({
                type: 'POST', dataType: 'json',
                url: ' /Apply/NQuerySixYouApplyInfo',
                async: false,
                data: JSON.stringify({ "token": postData.Head.Token }),
                contentType: 'application/json',
                error: function (data, status, headers, config) {
                    showTip(status);
                },
                success: function (data) {
                    if (data.IsHaveAllSixKey) {
                        window.location = '/Assessment/AssessStep2' + querystring + "#/step2";
                    } else {
                        window.location = '/Assessment/assessStep1' + querystring;
                    }
                }
            })
        }
        localStorage.setItem('applyThreeSteps', 'true');// 非登录状态下申请流程的步骤有三部// localStorage以字符串形成存值
    }
}

//从cookie取值
function getCookie(name) {
    var arr = document.cookie.split("; ");
    for (var i = 0; i < arr.length; i++) {
        var arr2 = arr[i].split("=");
        if (arr2[0] == name) {
            return arr2[1];
        }
    }
    return "";
}

//获取utmsource
var getUtmSource = function () {
    var cookieVal = Storage.Cookies.get("rongziUtm");
    var result = undefined;
    if (cookieVal) {
        var utmArray = cookieVal.split("&");
        if (utmArray && utmArray.length > 0) {
            var reg = /utm_source=(\d+)/i;
            utmArray.forEach(function (curVal) {
                var regResult = reg.exec(curVal);
                if (regResult && regResult.length == 2) {
                    result = regResult[1];
                }
            });
        }
    }
    return result;
}

//城市名简写
function simpleName(name) {
    if (name) {
        var sname = name;
        if (name.indexOf('市') > -1) {
            sname = name.replace('市', '');
        } else if (name.indexOf('地区') > -1) {
            sname = name.replace('地区', '');
        } else if (name.indexOf('自治州') > -1) {
            sname = name.replace('自治州', '');
        } else if (name.indexOf('自治县') > -1) {
            sname = name.replace('自治县', '');
        } else if (name.indexOf('行政区') > -1) {
            sname = name.replace('行政区', '');
        };
        if (name.length > 4) {
            sname = name.substring(0, 4)
            switch (sname) {
                case '恩施土家': sname = '恩施'; break;
                case '神农架林': sname = '神农架'; break;
                case '湘西土家': sname = '湘西'; break;
                case '阿坝藏族': sname = '阿坝'; break;
                case '黔南布依': sname = '黔南州'; break;
                case '黔东南苗': sname = '黔东南'; break;
                case '黔西南布': sname = '金州'; break;
                case '保亭黎族': sname = '宝停'; break;
                case '琼中黎族': sname = '琼中'; break;
                case '西双版纳': sname = '西双版纳'; break;
                case '德宏傣族': sname = '德宏'; break;
                case '红河哈尼': sname = '红河'; break;
                case '文山壮族': sname = '文山'; break;
                case '怒江傈傈': sname = '怒江'; break;
                case '海西蒙古': sname = '海西'; break;
                case '克孜勒苏': sname = '克州'; break;
                case '博尔塔拉': sname = '博州'; break;
                case '巴音郭楞': sname = '巴州'; break;
                case '伊犁哈萨': sname = '伊犁'; break;
                case '锡林郭勒': sname = '锡盟'; break;
                case '澳门特别': sname = '澳门'; break;
                case '香港特别': sname = '香港'; break;
            };
        }
        return sname;
    }
};

//获取页面搜索来源 D:直接搜索,S:百度SEO,U_xx:通过utm_Source
var getFromWebSite = function () {
    var cookieVal = Storage.Cookies.get("rongziUtm");
    var result = "D";
    if (cookieVal) {
        var utmArray = cookieVal.split("&");
        if (utmArray && utmArray.length > 0) {
            var regSeo = /refer=(\w+)/i;
            var regUtm = /utm_source=(\d+)/i;
            utmArray.forEach(function (curVal) {
                var regResultSeo = regSeo.exec(curVal);
                if (regResultSeo && regResultSeo.length > 0) {
                    result = "S";
                }
                var regResultUtm = regUtm.exec(curVal);
                if (regResultUtm && regResultUtm.length == 2) {
                    result = "U" + regResultUtm[1];
                }
            });
        }
    }
    return result;
}


//自定义scrollTo方法
$.fn.scrollTo = function (options) {
    var defaults = {
        toT: 0,    //滚动目标位置
        durTime: 500,  //过渡动画时间
        delay: 30,     //定时器时间
        callback: null   //回调函数
    };
    var opts = $.extend(defaults, options),
        timer = null,
        _this = this,
        curTop = _this.scrollTop(),//滚动条当前的位置
        subTop = opts.toT - curTop,    //滚动条目标位置和当前位置的差值
        index = 0,
        dur = Math.round(opts.durTime / opts.delay),
        smoothScroll = function (t) {
            index++;
            var per = Math.round(subTop / dur);
            if (index >= dur) {
                _this.scrollTop(t);
                window.clearInterval(timer);
                if (opts.callback && typeof opts.callback == 'function') {
                    opts.callback();
                }
                return;
            } else {
                _this.scrollTop(curTop + index * per);
            }
        };
    timer = window.setInterval(function () {
        smoothScroll(opts.toT);
    }, opts.delay);
    return _this;
};